package com.xxwy.simple.rpc.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @author wy
 * @date 2020/3/9 10:37
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

  private ChannelHandlerContext ctx;
  private String result;
  private String para;

  //与服务器的连接创建后，就会被调用
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    this.ctx = ctx;
  }

  @Override
  public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    this.result = msg.toString();
    //唤醒等待的线程
    notify();
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
    cause.printStackTrace();
  }

  /**
   * 被代理对象调用，发送数据给服务器: wait --> channelRead(被唤醒)
   * @return
   * @throws Exception
   */
  @Override
  public synchronized Object call() throws Exception {
    ctx.writeAndFlush(para);
    wait();
    return result;
  }

  public void setPara(String para) {
    this.para = para;
  }
}
